package com;

import java.io.IOException;


import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.naming.NamingException;

import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.domain.Message;
@Service
public class MessageService {
	@Resource
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	
	@Transactional(readOnly = true)
	public List<Message> getMessages() throws ClassNotFoundException, SQLException, IOException, NamingException {

		String query = "SELECT * FROM messages";
		List<Message> list = new ArrayList<Message>();

		ParameterizedRowMapper<Message> mapper = new ParameterizedRowMapper<Message>() {

			public Message mapRow(ResultSet rs, int rowNum) throws SQLException {
				Message message = new Message();
				message.setMessage(rs.getString("message"));
				message.setChatterName(rs.getString("name"));
				message.setTime(rs.getLong("time"));
				return message;
			}
		};

		list = (List<Message>) namedParameterJdbcTemplate.query(query, new HashMap(), mapper);

		return list;
	}
	@Transactional
	public void addMessage(String msg, String nickname) throws IOException, SQLException, NamingException{
		long time = System.currentTimeMillis();
		String query = "INSERT INTO messages(name, message, time) VALUES(:name,:message,:time);";
		Map namedParameters = new HashMap();
        namedParameters.put("name", nickname);
        namedParameters.put("message", msg);
        namedParameters.put("time", time);
		namedParameterJdbcTemplate.update(query, namedParameters);
	}
}
